﻿<!DOCTYPE html>
<html>
<head>
    <title>吴淞学区红色电影征文活动</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="asset/css/reset.css" />
    <link rel="stylesheet" type="text/css" href="asset/css/main.css" />
    <link rel="stylesheet" type="text/css" href="asset/css/dialog.css" />
    <script type="text/javascript">
        function GetQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }

        function getCookie(c_name) {
            if (document.cookie.length > 0) {
                c_start = document.cookie.indexOf(c_name + "=")
                if (c_start != -1) {
                    c_start = c_start + c_name.length + 1
                    c_end = document.cookie.indexOf(";", c_start)
                    if (c_end == -1) c_end = document.cookie.length
                    return unescape(document.cookie.substring(c_start, c_end))
                }
            }
            return ""
        }

        var _code = GetQueryString("code")

        if (_code === null && getCookie("user") === "") {

            window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb1f3698b4c90dccd&redirect_uri=http://www.shtraining.net/wx/index.html&response_type=code&scope=snsapi_base&state=1#wechat_redirec";
        }
    </script>
</head>
<body>
    <section class="wrapper">
        <div id="main_index" class="main"></div>
        <div id="main_vote" class="main hidden">
            <ul class="tab_title">
                <li class="active">WORD文档</li>
                <li>数字故事</li>
            </ul>
            <div class="tab_content" style="padding-bottom: 60px;">

                <!-- <div id="message">ok-1</div> -->
                <div id="list_words" class="waterfall">
                </div>
                <div id="list_videos" class="waterfall hidden">
                </div>

            </div>
        </div>
        <div id="main_rule" class="main hidden">
            <p id="rule_title">活动规则 </p>
            <ul id="list_rules">
                <li><p>1. 活动时间：<br />&nbsp;&nbsp;&nbsp;&nbsp;即日起至2018年12月28日。</p></li>
                <li><p>2. 投票规则：<br />&nbsp;&nbsp;&nbsp;&nbsp;活动期内每个微信用户总共可以投3票。</p></li>
                <li><p>3. 本活动解释权归主办方所有。</p></li>
            </ul>
        </div>
    </section>
    <div id="nav_main">
        <div class="left"><span href="index.html" class="nav_item" id="a_index"></span></div>
        <div class="left" style="width:calc(100% - 120px);"><span class="nav_item" id="a_vote"></span></div>
        <div class="right"><span class="nav_item" id="a_rule"></span></div>
    </div>

    <script id="list" type="text/html">
        {{each articles item index}}
        <div class="item">
            <div class="item-content">
                <a href="dj/{{item.ImageUrl}}.html"><img src="asset/images/dj_cover/{{item.ImageUrl}}.jpg" class="item-cover" /></a>

            </div>

            <div class="item-bar">
                <span class="thumbup_total" data_total="{{item.ThumbupCount}}">{{item.ThumbupCount}} 票</span>
                <span class="thumbup_btn" data_articleid="{{item.ArticleID}}">投票</span>
            </div>
        </div>
        {{/each}}
    </script>

    <script src="asset/js/template-web.js"></script>
    <script src="http://cdn.bootcss.com/zepto/1.1.4/zepto.min.js" type="text/javascript"></script>
    <script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>
    <script src="asset/js/selector.js" type="text/javascript"></script>
    <script src="asset/js/utils.js" type="text/javascript"></script>
    <script src="asset/js/dialog.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var user;
        var openId;
        var nickName;
        var headImgUrl;
        var getUserUrl;
        var getArticlesUrl;
        var toast;

        $(document).ready(function () {
            
            initPage();

            $(".tab_title li").click(function () {
                $(".tab_title li").removeClass("active");
                $(this).addClass("active");

                var index = $(".tab_title li").index(this);
                $(".waterfall").hide();
                $(".waterfall:eq(" + index + ")").show();
            });

        });

        function bindMenuClick() {
            $(".nav_item").click(function () {
                var menuToPage = $(this).attr("id").split("_")[1]
                setNavStatus(menuToPage);
                setContentStatus(menuToPage);
            });
        }

        function setNavStatus(id) {
            $("#a_index").css("background-image", "url('asset/images/btn_index.png')");
            $("#a_vote").css("background-image", "url('asset/images/btn_vote.png')");
            $("#a_rule").css("background-image", "url('asset/images/btn_rule.png')");

            $("#a_" + id).css("background-image", "url('asset/images/btn_" + id + "_focus.png')");
        }

        function setContentStatus(id) {
            $(".main").hide();
            $("#main_" + id).show();
        }

        function initPage() {
            //第一步检查cookie是否存在，如果存在就不用去访问微信服务器获取openid，直接使用cookies中的openid查询数据
            //库中的用户信息并写入cookie,如果不存在则访问微信服务器获取openid
            //第二步使用openid检查数据库中是否有该用户信息，如果数据库中没有，说明该用户是第一次登录，需要将用户信息
            //保存到数据库，然后取出用户信息并保存到cookie中；如果数据库中有，则取出用户信息保存到cookie中

            if (GetQueryString("back") == "a") {
                setNavStatus("vote");
                setContentStatus("vote");
            }

            bindMenuClick();

            user = getCookie("wusong_user");

            if (user != null && user != "") {

                openId = JSON.parse(user).OpenID;
                nickName = JSON.parse(user).NickName;

                getUserUrl = "api/user/" + openId;

                console.log(getUserUrl);

                axios.get(getUserUrl).then(function (response) {
                    console.log(response);
                    setCookie("wusong_user", JSON.stringify(response.data), 60);
                    getArtilces();
                });

            }
            else {


                var code = GetQueryString("code");

                var getTokenUrl = "api/accesstoken/?code=" + code;
                //var getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb1f3698b4c90dccd&secret=fb2c780dd9348a370b36724251d2fbd2&code="+code+"&grant_type=authorization_code"
                var userInfo;

                axios.get(getTokenUrl).then(function (response) {
                    console.log(response)
                    openId = response.data;
                    //var userInfo = response.data;
                    //openId = userInfo.openid;
                    //nickName = userInfo.nickname;
                    //headImgUrl = userInfo.headimgurl;

                    getUserUrl = "api/user/" + openId;

                    console.log(getUserUrl);

                    axios.get(getUserUrl).then(function (response) {
                        console.log("user is existed.")
                        console.log(response.data);
                        setCookie("wusong_user", JSON.stringify(response.data), 60);
                        getArtilces();

                    }).catch(function (error) {
                        if (error.response.status == "404") {
                            uploadUser();
                        }
                    });

                });

            }



        }

        function getVideos() {
            var getVideosUrl = "api/article/";

            $.ajax({
                url: getVideosUrl,
                dataType: "application/json",
                data: { "where": "and videourl is not null" },
                type: 'GET',
                error: function (error) {
                    console.log(error);
                },
                success: function (result) {

                    var data = JSON.parse("{\"articles\":" + result + "}");
                    var html = template("list", data);
                    $("#list_videos").html(html);

                    console.log("getVideos completed.");
                    user = getCookie("wusong_user");
                    console.log(JSON.parse(user).ThumbupCount);

                    bindThumbupClick();

                    //设置点赞按钮状态
                    if (JSON.parse(user).ThumbupCount >= 3) {
                        $(".thumbup_btn").css("background-color", "gray");
                        $(".thumbup_btn").unbind("click");
                    }
                },
                complete: function () {
                    toast.close();
                }
            });
        }

        function getArtilces() {

            var getArticlesUrl = "api/article/";

            $.ajax({
                url: getArticlesUrl,
                dataType: "application/json",
                type: 'GET',
                error: function (error) {
                    console.log(error);
                },
                beforeSend: function () {
                    toast = $(document).dialog({
                        type: 'toast',
                        infoIcon: 'asset/images/icon/loading.gif',
                        infoText: '正在加载中',
                        autoClose: 2500
                    });
                },
                success: function (result) {

                    var data = JSON.parse("{\"articles\":" + result + "}");
                    var html = template("list", data);
                    $("#list_words").html(html);
                    console.log(result)
                    console.log("getArticles completed.");
                    user = getCookie("wusong_user");
                    console.log(JSON.parse(user).ThumbupCount);

                    getVideos()
                    //bindThumbupClick();

                    //设置点赞按钮状态
                    if (JSON.parse(user).ThumbupCount >= 3) {
                        $(".thumbup_btn").css("background-color", "gray");
                        $(".thumbup_btn").unbind("click");
                    }
                }
            });
            
        }

        function bindThumbupClick() {
            $(".thumbup_btn").click(function () {

                console.log("thumbup_btn click.")

                var articleId = $(this).attr("data_articleId");

                var model = { "openid": openId, "nickname": nickName, "articleid": articleId };

                var span_thumbup_total = $(this).prev();

                $.ajax({
                    url: "api/thumbup/",
                    contentType: "application/json; charset=utf-8",
                    type: "POST",
                    data: JSON.stringify(model),
                    error: function (data) {
                        console.log(data);
                    },
                    success: function (data) {
                        console.log("ok");
                    },
                    complete: function () {

                        $.getJSON("api/article/" + articleId, function (data) {
                            span_thumbup_total.html(data.ThumbupCount + " 票");
                            //console.log(data.ThumbupCount);

                            $.getJSON("api/user/" + openId, function (data) {
                                setCookie("wusong_user", JSON.stringify(data), 60);
                                user = getCookie("wusong_user");
                                console.log(JSON.parse(user).ThumbupCount);

                                //设置点赞按钮状态
                                if (JSON.parse(user).ThumbupCount >= 3) {
                                    $(".thumbup_btn").css("background-color", "gray");
                                    $(".thumbup_btn").unbind("click");
                                }
                            });
                        });


                    }
                });
            });
        }

        function uploadUser() {

            //$("#message").html("ok-3");

            var model = { "OpenID": openId, "NickName": nickName, "HeadImgUrl": headImgUrl };

            $.ajax({
                url: "api/user/",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                data: JSON.stringify(model),
                error: function (data) {
                    console.log(data);
                },
                success: function (data) {
                    console.log("uploadUser is ok");
                },
                complete: function (data) {
                    $.getJSON("api/user/" + openId, function (data) {
                        setCookie("wusong_user", JSON.stringify(data), 60);
                        getArtilces();
                    });
                }
            });
        }
    </script>
</body>
</html>